package com.ocom.company.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.dto.UnitsPageOnShowDto;
import com.ocom.common.entity.access.EntityMjRegionInfo;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.human.EntityDeptInfo;
import com.ocom.common.entity.master.EntityCompanyList;
import com.ocom.common.entity.master.EntityCompanyPart;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.pojo.company.CompanyListPojo;
import com.ocom.common.request.company.GetCompanySummaryRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.CompanyListInfoVo;
import com.ocom.company.feign.AccessClient;
import com.ocom.company.feign.HumanClient;
import com.ocom.company.feign.PayConfigClient;
import com.ocom.company.service.*;
import com.ocom.common.vo.company.GetMngUserInfoVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class CompanyListController {



    //注入 companyInfoService 业务层
    @Autowired
    private CompanyListInfoService companyListInfoService;

    @Autowired
    private CompanyListService companyListService;

    //注入 companyInfoService 业务层
    @Autowired
    private MngUserInfoService mngUserInfoService;

    @Autowired
    private CompanyPartService companyPartService;

    @Autowired
    private XfMerchantInfoService xfMerchantInfoService;

    @Autowired
    private HumanClient humanClient;

    @Autowired
    private AccessClient accessClient;

    @Autowired
    private PayConfigClient payConfigClient;
    /**
     * 获取单位列表 一条
     */
    @PostMapping(CompanyServiceUrl.URL_GetCompanyListInfoOne)
    public Result GetCompanyListInfoOne(Long companyId) {
    //    System.out.println(companyId);
        EntityCompanyList entityCompanyList=companyListInfoService.GetCompanyListInfo(companyId);
        if(entityCompanyList==null){
            return ResultUtil.error(ResultEnum.Err_301);
        }else{
            return ResultUtil.success(entityCompanyList);
        }
    }

    /**
     * 获取单位列表信息
     */
    @PostMapping(CompanyServiceUrl.URL_GetCompanyListInfo)
    public Result GetCompanyListInfo(@RequestBody  CompanyListInfoVo companyListInfoVo) {
        List<EntityCompanyList> entityCompanyLists = companyListInfoService.GetCompanyListInfo(companyListInfoVo);

        PageInfo<EntityCompanyList> listPageInfo = new PageInfo<>(entityCompanyLists);
        List<UnitsPageOnShowDto> list = new ArrayList<>();
        for (EntityCompanyList entityCompanyList : entityCompanyLists) {
            UnitsPageOnShowDto companyListDto = new UnitsPageOnShowDto();
            companyListDto.setComId(entityCompanyList.getComId());
            companyListDto.setComName(entityCompanyList.getComName());
            companyListDto.setAgentId(entityCompanyList.getAgentId());
            companyListDto.setIsAgent(entityCompanyList.getIsAgent());
            companyListDto.setAgentName(entityCompanyList.getComName());
            companyListDto.setComId(entityCompanyList.getComId());
            companyListDto.setCreateTime(entityCompanyList.getCreateTime());
            companyListDto.setMjStatus(entityCompanyList.getMjStatus());
            companyListDto.setXfStatus(entityCompanyList.getXfStatus());
            companyListDto.setSaasNo(entityCompanyList.getSaasNo());
            companyListDto.setSaasId(entityCompanyList.getSaasId());
            companyListDto.setProvince(entityCompanyList.getProvince());
            companyListDto.setCity(entityCompanyList.getCity());
            GetMngUserInfoVo getMngUserInfoVo = new GetMngUserInfoVo();
            getMngUserInfoVo.setComId(entityCompanyList.getComId());
            EntityMngUserInfo entityMngUserInfo = mngUserInfoService.GetMngUserInfo(entityCompanyList.getComId(), getMngUserInfoVo);
            if (entityMngUserInfo == null) {
                list.add(companyListDto);
                continue;
            }
            if (entityMngUserInfo.getUserName() == null) {
                list.add(companyListDto);
                continue;
            }
            companyListDto.setUserName(entityMngUserInfo.getUserName());
            list.add(companyListDto);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", listPageInfo.getTotal());
        map.put("list", list);


        map.put("agents", companyListInfoService.getAgents());
        return ResultUtil.success(map);
    }

    @PostMapping(CompanyServiceUrl.URL_getCmpanyListByOpenid)
    public Result getCmpanyListByOpenid(String openid){
        log.info("获取单位列表 {{}}",openid);
        List<CompanyListPojo>  companyLists=companyListInfoService.getCompanyList(openid);
        Map<Long,EntityDeptInfo> deptInfoMap = new HashMap<>();
        Map<Long,EntityMjRegionInfo> regionInfoMap = new HashMap<>();
        Map<Integer,EntityXfMerchantInfo> xfMerchantInfoMap = new HashMap<>();
        if(companyLists==null || companyLists.size()==0){
            return ResultUtil.success(companyLists);
        }

        List<EntityCompanyPart> list = companyPartService.getDataSourceList();
        List<Long>  ids =  companyLists.stream().map(CompanyListPojo -> CompanyListPojo.getCompanyId()).collect(Collectors.toList());

        List<EntityXfMerchantInfo> merchantInfos= new ArrayList<>();
        for (EntityCompanyPart entityCompanyPart:list){
            List<EntityXfMerchantInfo>  machList =xfMerchantInfoService.getMerchList(entityCompanyPart.getBeginComId(),ids);
            if(machList!=null) merchantInfos.addAll(machList);
        }
        for (int i = 0;i<companyLists.size();i++){
            CompanyListPojo companyListPojo = companyLists.get(i);
            companyListPojo.setDeptName("");
            //部门
            if(companyListPojo.getDeptId() > 0){
                if(ObjectUtil.isNotEmpty(deptInfoMap.get(companyListPojo.getDeptId()))){
                    companyListPojo.setDeptName(companyListPojo.getDeptName()+deptInfoMap.get(companyListPojo.getDeptId()).getDeptName());
                }else{
                    EntityDeptInfo entityDeptInfo = new EntityDeptInfo();
                    entityDeptInfo.setComId(companyListPojo.getCompanyId());
                    entityDeptInfo.setDeptId(companyListPojo.getDeptId());
                    Result<EntityDeptInfo> resultA = this.humanClient.getDeptById(entityDeptInfo);
                    if(ObjectUtil.isNotEmpty(resultA.getData())){
                        companyListPojo.setDeptName(companyListPojo.getDeptName()+resultA.getData().getDeptName());
                        deptInfoMap.put(resultA.getData().getDeptId(),resultA.getData());
                    }
                }

            }

            //片区
            if(companyListPojo.getAreaId() > 0){
                if(ObjectUtil.isNotEmpty(regionInfoMap.get(companyListPojo.getAreaId()))){
                    companyListPojo.setDeptName(companyListPojo.getDeptName()+regionInfoMap.get(companyListPojo.getAreaId()).getRegionName());
                }else{
                    EntityMjRegionInfo entityMjRegionInfo = new EntityMjRegionInfo();
                    entityMjRegionInfo.setRegionId(companyListPojo.getAreaId());
                    entityMjRegionInfo.setComId(companyListPojo.getCompanyId());
                    Result<EntityMjRegionInfo> resultB  = this.accessClient.getMjRegionInfo(entityMjRegionInfo);
                    if(ObjectUtil.isNotEmpty(resultB.getData())){
                        companyListPojo.setDeptName(companyListPojo.getDeptName()+resultB.getData().getRegionName());
                        regionInfoMap.put(resultB.getData().getRegionId(),resultB.getData());
                    }
                }

            }


            if(companyListPojo.getMerchId() > 0){
                if(ObjectUtil.isNotEmpty(xfMerchantInfoMap.get(companyListPojo.getMerchId().intValue()))){
                    companyListPojo.setDeptName(companyListPojo.getDeptName()+xfMerchantInfoMap.get(companyListPojo.getMerchId().intValue()).getMerchName());
                }else{
                    Result<EntityXfMerchantInfo> resultC = payConfigClient.GetMerchInfo(companyListPojo.getCompanyId(),companyListPojo.getMerchId().intValue());
                    if(ObjectUtil.isNotEmpty(resultC.getData())){
                        companyListPojo.setDeptName(companyListPojo.getDeptName()+resultC.getData().getMerchName());
                        xfMerchantInfoMap.put(resultC.getData().getMerchId(),resultC.getData());
                    }
                }

            }
            companyLists.set(i,companyListPojo);
            if(companyListPojo.getRole()!=41l) continue;
            for (EntityXfMerchantInfo entityXfMerchantInfo:merchantInfos){
                if(entityXfMerchantInfo.getComId().equals(companyListPojo.getCompanyId())
                    && companyListPojo.getMerchId().equals(entityXfMerchantInfo.getMerchId().longValue())
                ){
                    companyListPojo.setMerchName(entityXfMerchantInfo.getMerchName());
                    companyLists.set(i,companyListPojo);
                    break;
                }
            }


        }

        log.info("获取返回单位列表 {{}}",companyLists);

        return ResultUtil.success(companyLists);
    }

    /**
     * 是否存在管理员
     * @param userName
     * @param password
     * @return
     */
    @DataSourceAspect()
    @PostMapping(CompanyServiceUrl.URL_isExistCompany)
    public Result isExistCompany(String userName,String password){

        QueryWrapper<EntityMngUserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        EntityMngUserInfo mngUserInfo = mngUserInfoService.getOne(queryWrapper);

        if(mngUserInfo==null){
            return ResultUtil.error(ResultEnum.Err_303);
        }

        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String hashPass = password+mngUserInfo.getSalt();
        boolean b= bcryptPasswordEncoder.matches(hashPass,mngUserInfo.getPassword());
        if(!b){
            return ResultUtil.error(ResultEnum.Err_303);
        }
        //1 为pid
        Map<String,Integer> map=new HashMap<>();
        map.put("comId",mngUserInfo.getComId().intValue());
        map.put("pId",mngUserInfo.getId().intValue());
        return  ResultUtil.success(map);
    }


    @PostMapping(CompanyServiceUrl.URL_getCompanyListByAgentId)
    public Result getCompanyListByAgentId(Long agentId){
        List<EntityCompanyList> lists = companyListInfoService.getCompanyListByAgentId(agentId);
        return  ResultUtil.success(lists);
//        return  ResultUtil.success((HashMap<Long, String>)lists.stream()
//                .filter(t -> t.getComId()!=null)
//                .collect(Collectors.toMap(EntityCompanyList::getComId,EntityCompanyList::getComName,(k1, k2)->k2)));
    }

//获取单位简表
    @PostMapping(CompanyServiceUrl.URL_getCompanySummary)
    public Result getCompanySummary(@RequestBody GetCompanySummaryRequest getCompanySummaryRequest) {
        List<EntityCompanyList> entityCompanyList = companyListInfoService.getCompanySummary(getCompanySummaryRequest);
        PageInfo<EntityCompanyList> listPageInfo = new PageInfo<>(entityCompanyList);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for (EntityCompanyList companyList : listPageInfo.getList()) {
            Map<String,Object> map=new HashMap<>();
            map.put("comId",companyList.getComId());
            map.put("comName",companyList.getComName());
            map.put("isAgent",companyList.getAgentId());
            map.put("agentId",companyList.getAgentId());
            map.put("saasNo",companyList.getSaasId());
            map.put("xfVer",companyList.getXfStatus());
            map.put("mjVer",companyList.getMjStatus());
            map.put("province",companyList.getProvince());
            map.put("city",companyList.getCity());
            map.put("district",companyList.getDistrict());
            map.put("subDb",getCompanySummaryRequest.getSubDb());
            map.put("comStatus",companyList.getComStatus());
            map.put("endTime",companyList.getEndTime());
            map.put("createTime",companyList.getCreateTime());

            /**
             * maxUserNum	最大用户数	int
             * maxXfMachNum	最大消费设备数	int
             * maxMfMachNum	最大门禁设备数	int
             * maxTableNum	最大取餐点数	int
             * maxChannelNum	最大支付通道数	int
             * province	省	string
             * city	市	string
             * district	区、县	string
             */
            map.put("maxUserNum",companyList.getMaxUserNum());
            map.put("maxXfMachNum",companyList.getMaxXfMachNum());
            map.put("maxMjMachNum",companyList.getMaxMjMachNum());
            map.put("maxTableNum",companyList.getMaxTableNum());
            map.put("maxChannelNum",companyList.getMaxChannelNum());
            map.put("province",companyList.getProvince());
            map.put("city",companyList.getCity());
            map.put("district",companyList.getDistrict());

            mapList.add(map);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", listPageInfo.getTotal());
        map.put("list", mapList);
        return ResultUtil.success(map);
    }

    @PostMapping(CompanyServiceUrl.getXcxComList)
    public Result getXcxComList(@RequestParam List<Long> comIds){
        List<EntityCompanyList> list=companyListService.selectByIds(comIds);
        if(list!=null){
            return ResultUtil.success(list);
        }else{
            return ResultUtil.error(ResultEnum.Err_1001);
        }
    }
}
